package com.wallet.my.service.impl;

import com.wallet.my.service.ContractService;
import com.wallet.my.util.EthUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.methods.request.Transaction;
import org.web3j.utils.Convert;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;

/**
 * 合约接口实现类
 **/
@Service
public class ContractServiceImpl implements ContractService {
    @Autowired
    private Web3j web3j;                                               //加载初始化后的web3j对象，已经配置测试网kovan连接点
    @Autowired
    private EthUtil ethUtil;

//    部署合约
    @Override
    public Map<String, Object> newContract(String fromAddr, String privateKey,String data,BigDecimal money, BigInteger gasLimit) {
        BigInteger nonce = ethUtil.getNonce(web3j,fromAddr);
        // 存入金额转换成wei
        BigInteger value = Convert.toWei(money, Convert.Unit.ETHER).toBigInteger();
        //获取全网平均gasprice
        BigInteger gasPrice = ethUtil.getMyGasPrice(web3j);
        // 构建合约交易
        Transaction transaction = Transaction.createContractTransaction(fromAddr, nonce, gasPrice, gasLimit,value,data);
        // 估算gasLimit
        BigInteger estimateGasLimit = ethUtil.getEstimateGasLimit(web3j,transaction);
        //查询余额
        BigDecimal myBalance = ethUtil.getMyBalance(web3j,fromAddr);
        // 判断余额是否充足
        boolean isEnough = ethUtil.balanceIsEnough(myBalance,value,estimateGasLimit,gasPrice);
        if (isEnough == false) {
            throw new RuntimeException("余额不足，请确认后再转账");
        } else {                     //调用签名方法，并发送交易
            String transHash = null;
            HashMap<String, Object> map = new HashMap<>();
            if (transHash == null) {
                map.put("code", "1");
                map.put("message", "error");
                map.put("error", transHash);
            }else {
                map.put("code", "200");
                map.put("message","ok");
                map.put("transHash",transHash);
            }
            return map;
        }

    }
}
